package com.yizhang.xml.processor;

import com.yizhang.xml.dao.impl.UserDaoImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-06-06 10:54:03
 * @Description: Bean后置处理器
 */
public class MyBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor.postProcessBeforeInitialization执行=====================");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor.postProcessAfterInitialization执行=====================");
        if (bean.getClass().equals(UserDaoImpl.class)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 动态代理
            Object o = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理前的时间：" + sdf.format(new Date()));
                    method.invoke(bean, args);
                    System.out.println("代理后的时间：" + sdf.format(new Date()));
                    return proxy;
                }
            });
            return o;
        }
        return bean;
    }
}
